package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.service.TestService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author: atguigu
 * @create: 2025-03-21 11:31
 */
@Slf4j
@Service
public class TestServiceImpl implements TestService {

    @Autowired
    private RedissonClient redissonClient;


    @Override
    public String read(long id) {
        //1.获取读写锁对象
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("lock:" + id);
        //2.获取读锁
        RLock lock = readWriteLock.readLock();
        lock.lock(5, TimeUnit.SECONDS);
        try {
            //3.执行读数据业务
            log.info("读锁加锁成功,执行读数据业务");
            return "result:" + id;
        } finally {
            //4.释放读锁  TODO 故意不释放锁，等5后自动释放
            //lock.unlock();
        }
    }

    @Override
    public void write(long id) {
        //1.获取读写锁对象
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("lock:" + id);
        RLock lock = readWriteLock.writeLock();

        //2.获取写锁
        lock.lock(5, TimeUnit.SECONDS);

        //3.执行写数据业务
        try {
            log.info("写锁加锁成功,执行写数据业务");
        } finally {
            //4.释放写锁 TODO 故意不释放锁，等5后自动释放
            //lock.unlock();
        }
    }
}
